package com.steamedfish.auctioncloudprocess.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.steamedfish.auctioncloudprocess.entiry.AuctionBidEntity;
import com.steamedfish.auctioncloudprocess.entiry.UserEntiry;
import com.steamedfish.auctioncloudprocess.feign.client.AuctionItemClient;
import com.steamedfish.auctioncloudprocess.mapper.AuctionBidMapper;
import com.steamedfish.auctioncloudprocess.model.AuctionItemModel;
import com.steamedfish.auctioncloudprocess.model.BidsModel;
import com.steamedfish.auctioncloudprocess.task.TaskScheduler;
import com.steamedfish.auctioncloudprocess.utils.DateTimeUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 高山福
 * @since 2021-03-31
 */
@RestController
@RequestMapping("/auctioncloudprocess/auctionBidEntity")
public class AuctionBidController {

    @Autowired
    private AuctionBidMapper auctionBidMapper;

    @Autowired
    private TaskScheduler taskScheduler;

    @Autowired
    private AuctionItemClient auctionItemClient;


    @RequestMapping(value = "/bid", method = RequestMethod.POST)
    public ResponseEntity<?> bid(HttpServletRequest request,
                                 HttpServletResponse response,
                                 @RequestBody AuctionBidEntity data) throws ParseException, SchedulerException {

        System.out.println(JSON.toJSON(data));

        //获取用户信息
        String userToken = null;
        UserEntiry userEntiry = null;
        String userId = null;
        try {
            userToken = SecurityContextHolder.getContext().getAuthentication().getName();
            userEntiry = JSON.parseObject(userToken, UserEntiry.class);
            userId = userEntiry.getId();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("failed:没有登陆");
        }

        //生成竞拍表字段
        String id = "auction_bid_" + UUID.randomUUID();
        LocalDateTime createTime = LocalDateTime.now();
        String deleted = "0";

        //封装
        AuctionBidEntity auctionBidEntity = new AuctionBidEntity();
        auctionBidEntity.setId(id);
        auctionBidEntity.setItemId(data.getItemId());
        auctionBidEntity.setUserId(userId);
        auctionBidEntity.setBid(data.getBid());
        auctionBidEntity.setCreateTime(createTime);
        auctionBidEntity.setDeleted(deleted);

        //插入数据库
        auctionBidMapper.insert(auctionBidEntity);


        try {
            taskScheduler.triggerAuctionResultAdTask(auctionBidEntity.getItemId(), getEndTime(auctionBidEntity.getItemId()));
        } catch (Exception e) {

        }


        return ResponseEntity.ok("success");
    }


    @RequestMapping(value = "/getbids", method = RequestMethod.POST)
    public ResponseEntity<?> getBids(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @RequestBody AuctionBidEntity data){


        //获取用户信息
        String userToken = null;
        UserEntiry userEntiry = null;
        String userId = null;
        try {
            userToken = SecurityContextHolder.getContext().getAuthentication().getName();
            userEntiry = JSON.parseObject(userToken, UserEntiry.class);
            userId = userEntiry.getId();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok("failed:没有登陆");
        }

        //判断itemId是否为空
        if (data.getItemId() == null || data.getItemId().equals("")) {
            return ResponseEntity.ok("failed:商品id不能为空");
        }

        //查询
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("item_id", data.getItemId());
        queryWrapper.orderByDesc("bid");
        List<AuctionBidEntity> auctionBidEntities = auctionBidMapper.selectList(queryWrapper);

        //封装
        final String userId1 = userId;
        BidsModel bidsModel = new BidsModel();
        List<AuctionBidEntity> all = new ArrayList<>();
        List<AuctionBidEntity> self = new ArrayList<>();
        for (AuctionBidEntity e : auctionBidEntities) {
            if (e.getUserId().equals(userId1)) {
                self.add(e);
                all.add(e);
            } else {
                all.add(e);
            }
        }
        bidsModel.setSelf(self);
        bidsModel.setAll(all);
        try {
            bidsModel.setSelfHighest(self.get(0).getBid().toString());
        } catch (Exception e) {

        }


        return ResponseEntity.ok(bidsModel);

    }





    /**
     * 获取拍品结束的时间
     *
     * @param id
     * @return int
     */
    public Date getEndTime(String id) throws ParseException {
        AuctionItemModel auctionItemModel = auctionItemClient.getAuctionItemModel(id);
        String time = auctionItemModel.getEndTime();
        Date date = DateTimeUtils.StringToDate(time);
        Date afterDate = DateTimeUtils.afterTime(date, 30000);
        return afterDate;
    }
}
